/**
 * Copyright (C) 2009-2012, KingHool.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses.
 */
package com.kinghool.smodel.def;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.kinghool.ebos.commons.utils.Assert;
import com.kinghool.ebos.commons.utils.NameHelper;
import com.kinghool.ebos.commons.utils.Utils;
import com.kinghool.smodel.IModel;
import com.kinghool.smodel.ITreeModel;
import com.kinghool.smodel.rule.ChildCountRule;
import com.kinghool.smodel.rule.IModelRule;

/**
 * 
 * @Author Allen Deng(dengtailin@gmail.com) 
 */
public class TreeModelDefinition extends ModelDefinition {
	protected List<String> childrenSequence = Utils.newList();
	protected Map<String, TreeModelDefinition> children = Utils.newMap();
	protected TreeModelDefinition parent;
	protected boolean keepChildOrder = true;
 
	public TreeModelDefinition(String id) {
		super(id);
	}  
	
	public static TreeModelDefinition createDefaultTreeModelDefinition(String id) {
		return createDefaultTreeModelDefinition(id, null);
	}
	
	public static TreeModelDefinition createDefaultTreeModelDefinition(String id, TreeModelDefinition parent) {
		TreeModelDefinition modelDef = new TreeModelDefinition(id);
		modelDef.setCaseSensitive(true);
		modelDef.setIgnoreCheck(true);
		modelDef.setParent(parent);
		return modelDef;
	}
	
	public static TreeModelDefinition getNotNullChildTreeModelDefinition(String childId, TreeModelDefinition modelDefinition) {
		TreeModelDefinition rtnChildModelDef = createDefaultTreeModelDefinition(childId, modelDefinition);
		if (modelDefinition != null) {
			TreeModelDefinition childModelDef = modelDefinition.getChildModelDefinition(childId);
			if (childModelDef != null) {
				rtnChildModelDef = childModelDef;
			}
		}
		return rtnChildModelDef;
	}
	
	public TreeModelDefinition getRoot(){
		TreeModelDefinition root = this;
		while (root.getParent() != null) {
			root = root.getParent();
		}
		return root;
	}
	
	
	public TreeModelDefinition getParent() {
		return parent;
	} 

	public void setParent(TreeModelDefinition parent) {
		this.parent = parent;
	} 
	 
	public TreeModelDefinition getChildModelDefinition(String childFullName) {
        String[] childNames = NameHelper.parseFullName(childFullName);
          
        TreeModelDefinition root = this;
		for (int i = 0; i < childNames.length; i++) {
			if (root == null) {
				break;
			}
			String childName = formatPropertyName(childNames[i]);
			root = root.children.get(childName);
		}
		return root;
	}
	
	public String[] getChildrenSequence() {
		return childrenSequence.toArray(new String[0]);
	}
	
	public void installChild(TreeModelDefinition child) {
		String childName = formatPropertyName(child.getId());
		if (! children.containsKey(childName)) {
			childrenSequence.add(childName);
			children.put(childName, child);
			child.setParent(this);
		}
	}
	
	public boolean isMandantory() {
		if (parent != null) {
			return parent.isChildMandantory(getId());
		}
		return true;//the root element(parent == null) is mandantory
	}  
	
	public boolean isIgnoreCheck() {
		if (getParent() != null) {
			return getParent().isIgnoreCheck();
		}
		return ignoreCheck;
	}

	public void setIgnoreCheck(boolean ignoreCheck) {
		if (getParent() != null) {
			getParent().setIgnoreCheck(ignoreCheck);
		} else {
			this.ignoreCheck = ignoreCheck;
		}
	}
	
	public boolean isCaseSensitive() {
		if (getParent() != null) {
			return getParent().isCaseSensitive();
		}
		return caseSensitive;
	}
	
	public void setCaseSensitive(boolean caseSensitive) {
		if (getParent() != null) {
		   getParent().setCaseSensitive(caseSensitive);
		} else {
			this.caseSensitive = caseSensitive;
		}
	}
	
	public boolean isChildMandantory(String childFullName) {  
		// get the parent of childFullName
		TreeModelDefinition childParentDefinition = getChildModelDefinition(NameHelper.getParentFullName(childFullName));
		//check its parent has install ChildCount == 1 rule
		if (childParentDefinition != null) {
			for (IModelRule rule : rules) {
				if (rule instanceof ChildCountRule) {
 					if (((ChildCountRule)rule).isMandatory(formatPropertyName(NameHelper.getChildName(childFullName)))) {
 						return true;
 					}
				}
			}
		}
		return false;
	} 
	
	public boolean isTreeChild(String childFullName) {
		if (isIgnoreCheck()) return true;
		
		// get the parent of childFullName
		TreeModelDefinition childParentDefinition = getChildModelDefinition(NameHelper.getParentFullName(childFullName));
		if (childParentDefinition != null) {
			String childName = NameHelper.getChildName(childFullName);
			
			return childParentDefinition.childrenSequence.contains(formatPropertyName(childName));
		}
		return false;
	} 

	@SuppressWarnings("unchecked")
	public TreeModelDefinition clone() throws CloneNotSupportedException {
		TreeModelDefinition clone = (TreeModelDefinition) super.clone();
		clone.childrenSequence = (List<String>) ((ArrayList<String>)childrenSequence).clone();
		
		clone.children = Utils.newMap();
		for (String childName : children.keySet()) {
			TreeModelDefinition cloneChild = children.get(childName).clone();
			
			//set parent of clone child, do not clone parent to keep relation.
			cloneChild.parent = clone;
			
			clone.children.put(childName, cloneChild);
		}
		
		return clone;
	}
	
	protected List<String> getWarningMessages(IModel model) {
		List<String> warnMsgs = super.getWarningMessages(model); 
		
		if (model instanceof ITreeModel) {
			ITreeModel treeModel = (ITreeModel) model;
			for (String childName : children.keySet()) {
				TreeModelDefinition modelDef = children.get(childName);
				if (modelDef != null) {
					List<ITreeModel> childrenModel = treeModel.getTreeChild(childName);			
					for (ITreeModel childModel : childrenModel) {
						List<String> childWarnMsgs= modelDef.getWarningMessages(childModel);
						if (!Assert.isNullOrEmpty(childWarnMsgs)){								
							warnMsgs.addAll(childWarnMsgs);
						}						
					}
				}
			}
		}
		return warnMsgs;
	}
	
	protected List<String> getErrorMessages(IModel model) {
		List<String> errMsgs = super.getErrorMessages(model);
		
		if (model instanceof ITreeModel) {
			ITreeModel treeModel = (ITreeModel) model;
			
			//check the child whether defined, error if not defined.
			boolean valid = ignoreCheck ? true : children.keySet().containsAll(treeModel.getChildNames());
			if (! valid) {
				List<String> dest = new ArrayList<String>(treeModel.getChildNames()); 
				dest.removeAll(children.keySet());
				errMsgs.add("Bad format for the model:\n" +
						        "The model ["+ model.toString() + "] has undefined children:" + dest);
			}
			
			if (valid) {
				for (String childName : children.keySet()) {
					TreeModelDefinition childModeDef = children.get(childName);
					List<ITreeModel> childrenModel = treeModel.getTreeChild(childName);

					for (ITreeModel childModel : childrenModel) {
						List<String> childErrMsgs = childModeDef.getErrorMessages(childModel);							
						if (!Assert.isNullOrEmpty(childErrMsgs)) {
							errMsgs.addAll(childErrMsgs);
						}						
					}
				}
			}
		}
		return errMsgs;
	}

	public boolean isKeepChildOrder() {
		if (getParent() != null) {
			return getParent().isKeepChildOrder();
		}
		return keepChildOrder;
	}

	public void setKeepChildOrder(boolean keepChildOrder) {
		if (getParent() != null) {
		    getParent().setKeepChildOrder(keepChildOrder);
		} else {
			this.keepChildOrder = keepChildOrder;
		}
	}
}
